package com.wangweixiong.role.service.impl;

import com.wangweixiong.role.bean.RoleBean;
import com.wangweixiong.role.bean.RoleUserBean;
import com.wangweixiong.role.dao.RoleDao;
import com.wangweixiong.role.dao.UserRoleDao;
import com.wangweixiong.role.service.RoleService;
import com.wangweixiong.utils.DaoFactory;

import java.util.List;


public class RoleServiceImpl implements RoleService {
    private RoleDao roleDao;
    private UserRoleDao userRoleDao;

    @Override
    public Integer addRole(RoleBean roleBean) {
        DaoFactory<RoleDao> roleDaoFactory = new DaoFactory();
        roleDao =roleDaoFactory.getDaoTransaction(RoleDao.class);
        String name = roleBean.getName();
        // 若从数据库获得数据，证明角色重复
        boolean flag=roleDao.findAllRoleByName(name)==null;
        System.out.println(flag);
        if(flag){
            return roleDao.addRole(name);
        }
        System.out.println();
        return 0;
    }

    @Override
    public List<Integer> deleteRoleById(Object ids) {
        DaoFactory<RoleDao> roleDaoFactory = new DaoFactory();
        roleDao =roleDaoFactory.getDaoTransaction(RoleDao.class);
        List<Integer> idList=(List<Integer>)ids;
        DaoFactory<UserRoleDao> userRoleDaoFactory = new DaoFactory();
        userRoleDao =userRoleDaoFactory.getDao(UserRoleDao.class);
        List<Integer> byRoleId = userRoleDao.findByRoleId(idList);
        Integer size=byRoleId.size();
        System.out.println(size);
        if(byRoleId.size()==0){
            Integer rs=roleDao.deleteRole(idList);
            System.out.println(rs);
        }
        return byRoleId;
    }

    @Override
    public Integer updateRole(Integer id,String name) {
        DaoFactory<RoleDao> roleDaoFactory = new DaoFactory();
        roleDao =roleDaoFactory.getDaoTransaction(RoleDao.class);
        // 若从数据库获得数据，证明角色重复
        boolean flag=roleDao.findAllRoleByName(name)==null;
        System.out.println(flag);
        if(flag){
            return roleDao.updateRole(id,name);
        }
        return 0;
    }

    @Override
    public List<RoleUserBean> findAllRole(Integer userId) {

        DaoFactory<RoleDao> roleDaoFactory = new DaoFactory();
        roleDao =roleDaoFactory.getDao(RoleDao.class);
        List<RoleBean> roleBeans = roleDao.findRoleNameByUserId(userId);
        for(RoleBean roleBean:roleBeans){
            String name = roleBean.getName();
            if(name.equals("系统管理员")){
                List<RoleUserBean> allRole = roleDao.findAllRole();
                System.out.println(allRole);
                return allRole;
            }
        }

        return null;
    }
}
